package com.leetcode.array;

import java.util.TreeMap;

public class ContinuousSubarrays {
    public long continuousSubarrays(int[] nums) {
        TreeMap<Integer, Integer> treeMap = new TreeMap<>();
        long res = 0;
        int left = 0;
        for (int right = 0; right < nums.length; right++) {
            treeMap.merge(nums[right], 1, Integer::sum);
            while(treeMap.lastKey() - treeMap.firstKey() > 2) {
                int key = nums[left++];
                if (treeMap.get(key) == 1) {
                    treeMap.remove(key);
                } else {
                    treeMap.merge(key, -1, Integer::sum);
                }
            }
            res += right - left + 1;
        }
        return res;
    }
}
